package com.ipc.app.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ipc.app.biz.UserBiz;
import com.ipc.app.constants.SessionConstants;
import com.ipc.app.model.User;
import com.ipc.app.web.form.LoginForm;

/**
 * @author haijie.zhang
 * 
 */

@Controller
@RequestMapping(value = "/jsp/login.do")
public class LoginAction {

	@Autowired
	private Validator validator;

	@Autowired
	private UserBiz userBiz;

	@RequestMapping(method = RequestMethod.GET)
	public String loginView(ModelMap model) {
		model.addAttribute("loginForm", new LoginForm());
		return "login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String login(@ModelAttribute("loginForm")
	LoginForm loginForm, BindingResult result, HttpServletRequest request) {
		validator.validate(loginForm, result);
		if (result.hasErrors()) {
			return "login";
		}

		User user = userBiz.login(loginForm.getMobile(), loginForm
				.getPassword());
		if (null == user) {
			ObjectError error = new ObjectError("error.login", "error.login");
			result.addError(error);
			return "login";

		}

		HttpSession session = request.getSession(true);
		session.setAttribute(SessionConstants.LOGIN_USER_ID, user.getUserId());
		session.setAttribute(SessionConstants.LOGIN_USER_NAME, user
				.getUserName());
		session.setAttribute(SessionConstants.LOGIN_USER_TYPE, user
				.getUserType());

		return "loginSuccess";
	}
}
